#!/bin/bash

# 服务器环境检查脚本
# 在云服务器上运行此脚本以检查部署环境

echo "======================================"
echo "  MQTT项目服务器环境检查"
echo "======================================"
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查结果统计
PASS=0
FAIL=0

# 检查函数
check_command() {
    if command -v $1 &> /dev/null; then
        echo -e "${GREEN}✓${NC} $2: $(command -v $1)"
        PASS=$((PASS+1))
        return 0
    else
        echo -e "${RED}✗${NC} $2: 未安装"
        FAIL=$((FAIL+1))
        return 1
    fi
}

# 检查版本
check_version() {
    if command -v $1 &> /dev/null; then
        VERSION=$($1 $2 2>&1)
        echo -e "${GREEN}✓${NC} $3: $VERSION"
        PASS=$((PASS+1))
        return 0
    else
        echo -e "${RED}✗${NC} $3: 未安装"
        FAIL=$((FAIL+1))
        return 1
    fi
}

# 检查端口
check_port() {
    if netstat -tuln 2>/dev/null | grep -q ":$1 "; then
        echo -e "${YELLOW}!${NC} 端口 $1: 已被占用"
        echo "   使用命令查看: netstat -tuln | grep $1"
        return 1
    else
        echo -e "${GREEN}✓${NC} 端口 $1: 可用"
        PASS=$((PASS+1))
        return 0
    fi
}

# 1. 检查操作系统
echo "1. 操作系统信息"
echo "   系统: $(uname -s)"
echo "   内核: $(uname -r)"
echo "   架构: $(uname -m)"
echo ""

# 2. 检查必需软件
echo "2. 必需软件检查"
check_command node "Node.js"
check_version node "-v" "Node.js版本"
check_command npm "npm"
check_version npm "-v" "npm版本"
check_command git "Git"
check_command mysql "MySQL客户端"
echo ""

# 3. 检查可选软件
echo "3. 可选软件检查"
check_command pm2 "PM2"
if [ $? -eq 0 ]; then
    pm2 -v
fi
check_command nginx "Nginx"
check_command firewall-cmd "防火墙"
echo ""

# 4. 检查端口可用性
echo "4. 端口可用性检查"
check_port 3002
check_port 8081
check_port 3307
echo ""

# 5. 检查MySQL连接
echo "5. MySQL数据库检查"
if command -v mysql &> /dev/null; then
    echo "   尝试连接MySQL..."
    if mysql -h 8.149.243.80 -P 3307 -u root -p123456 -e "SELECT 1;" 2>/dev/null; then
        echo -e "${GREEN}✓${NC} MySQL连接成功"
        PASS=$((PASS+1))

        # 检查数据库
        if mysql -h 8.149.243.80 -P 3307 -u root -p123456 -e "USE mqtt_app;" 2>/dev/null; then
            echo -e "${GREEN}✓${NC} 数据库 mqtt_app 存在"
            PASS=$((PASS+1))
        else
            echo -e "${RED}✗${NC} 数据库 mqtt_app 不存在"
            FAIL=$((FAIL+1))
        fi
    else
        echo -e "${RED}✗${NC} MySQL连接失败"
        echo "   请检查："
        echo "   - MySQL服务是否运行"
        echo "   - 连接信息是否正确（主机、端口、用户名、密码）"
        echo "   - 防火墙是否开放3307端口"
        FAIL=$((FAIL+1))
    fi
else
    echo -e "${YELLOW}!${NC} MySQL客户端未安装，跳过连接测试"
fi
echo ""

# 6. 检查网络
echo "6. 网络检查"
PUBLIC_IP=$(curl -s ifconfig.me 2>/dev/null || echo "无法获取")
echo "   公网IP: $PUBLIC_IP"
if [ "$PUBLIC_IP" == "8.149.243.80" ]; then
    echo -e "${GREEN}✓${NC} 公网IP匹配"
    PASS=$((PASS+1))
else
    echo -e "${YELLOW}!${NC} 公网IP不匹配（期望: 8.149.243.80）"
fi
echo ""

# 7. 检查磁盘空间
echo "7. 磁盘空间检查"
DISK_USAGE=$(df -h / | tail -1 | awk '{print $5}' | sed 's/%//')
echo "   根分区使用率: ${DISK_USAGE}%"
if [ "$DISK_USAGE" -lt 80 ]; then
    echo -e "${GREEN}✓${NC} 磁盘空间充足"
    PASS=$((PASS+1))
else
    echo -e "${YELLOW}!${NC} 磁盘使用率较高，建议清理"
fi
echo ""

# 8. 检查内存
echo "8. 内存检查"
TOTAL_MEM=$(free -m | grep Mem | awk '{print $2}')
FREE_MEM=$(free -m | grep Mem | awk '{print $7}')
echo "   总内存: ${TOTAL_MEM}MB"
echo "   可用内存: ${FREE_MEM}MB"
if [ "$FREE_MEM" -gt 500 ]; then
    echo -e "${GREEN}✓${NC} 内存充足"
    PASS=$((PASS+1))
else
    echo -e "${YELLOW}!${NC} 可用内存较低"
fi
echo ""

# 9. 防火墙检查（如果有）
echo "9. 防火墙检查"
if command -v firewall-cmd &> /dev/null; then
    if firewall-cmd --state 2>/dev/null | grep -q "running"; then
        echo "   防火墙状态: 运行中"
        echo "   检查开放端口..."

        for port in 3002 8081 3307; do
            if firewall-cmd --list-ports 2>/dev/null | grep -q "${port}/tcp"; then
                echo -e "   ${GREEN}✓${NC} 端口 ${port}/tcp 已开放"
            else
                echo -e "   ${RED}✗${NC} 端口 ${port}/tcp 未开放"
                echo "      开放命令: firewall-cmd --permanent --add-port=${port}/tcp && firewall-cmd --reload"
            fi
        done
    else
        echo "   防火墙状态: 未运行"
    fi
else
    echo "   firewall-cmd 未安装，请手动检查防火墙配置"
fi
echo ""

# 总结
echo "======================================"
echo "  检查完成"
echo "======================================"
echo -e "通过: ${GREEN}${PASS}${NC} 项"
echo -e "失败: ${RED}${FAIL}${NC} 项"
echo ""

if [ $FAIL -eq 0 ]; then
    echo -e "${GREEN}✓ 环境检查全部通过，可以开始部署！${NC}"
    exit 0
else
    echo -e "${YELLOW}! 发现 ${FAIL} 个问题，请修复后再部署${NC}"
    echo ""
    echo "常见问题解决："
    echo "1. 安装Node.js: curl -fsSL https://rpm.nodesource.com/setup_16.x | bash - && yum install -y nodejs"
    echo "2. 安装PM2: npm install -g pm2"
    echo "3. 开放防火墙端口: firewall-cmd --permanent --add-port={3002,8081}/tcp && firewall-cmd --reload"
    echo "4. 检查MySQL服务: systemctl status mysql"
    exit 1
fi
